package com.zy.stock.controller;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.stock.domain.Account;
import com.zy.stock.domain.Pager;
import com.zy.stock.domain.Stock;
import com.zy.stock.domain.User;
import com.zy.stock.dto.StockDto;
import com.zy.stock.service.AccountService;
import com.zy.stock.service.UserService;
import com.zy.stock.util.CommonUtils;

@Controller
public class UserController {

	private Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService service;
	
	@Autowired
	private AccountService accountService;

	/**
	 * 新增用户
	 * */
	@ResponseBody
	@RequestMapping(value = "/user/add")
	public String addUser(User user) {
		user.setPassword(CommonUtils.MD5(user.getPassword()));
		long start = System.currentTimeMillis();
		try {
		    user.setType(1);
			service.save(user);
		} catch (Exception e) {
			logger.error(e.toString());
			return CommonUtils.resultJsonString(1, "error");
		} finally {
			logger.info("runing function addUser use times : " + (System.currentTimeMillis() - start));
		}
		return CommonUtils.resultJsonString(0, "succ");
	}

	@ResponseBody
	@RequestMapping(value = "/user/updateUser")
	public Integer updateUser(User user) {
		long start = System.currentTimeMillis();
		String pwd = user.getPassword();
		user.setPassword(CommonUtils.MD5(pwd));
		try {
			service.updateUser(user);
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			logger.info("runing function updateUser use times : " + (System.currentTimeMillis() - start));
		}
		return 0;
	}

	@RequestMapping(value = "/userManager")
	public ModelAndView toUserManager() {
		long start = System.currentTimeMillis();
		ModelAndView mav = new ModelAndView("userManager");
		mav.addObject("menuid", 7);
		long end = System.currentTimeMillis();
		logger.info("runing userManager function use times :" + (end - start));
		return mav;
	}

	@ResponseBody
	@RequestMapping(value = "/user/getUsersById")
	public String getUsersById(HttpServletRequest request) {
		String result = "";
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			Map<String, Object> map = new HashMap<String, Object>();
			StringWriter writer = new StringWriter();
			User user = service.findById(id);
			map.put("data",user);
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@ResponseBody
	@RequestMapping(value = "/user/deleteUsersById")
	public Integer deleteUsersById(HttpServletRequest request) {
		long start = System.currentTimeMillis();
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			service.deleteById(id);
			return 0;
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			logger.info("runing function deleteUsersById use times : " + (System.currentTimeMillis() - start));
		}
	}

	@ResponseBody
	@RequestMapping(value = "/user/getUsersByName")
	public String getUsersByName(HttpServletRequest request) {
		String result = "";
		try {
			Integer draw = Integer.parseInt(request.getParameter("draw"));
			Integer start = Integer.parseInt(request.getParameter("start"));
			Integer length = Integer.parseInt(request.getParameter("length"));
			String userName = request.getParameter("userName");
			String orderColumn = request.getParameter("order[0][column]");
			String columnName = request.getParameter("columns[" + orderColumn + "][data]");
			String orderDir = request.getParameter("order[0][dir]");
			Map<String, Object> map = new HashMap<String, Object>();
			ObjectMapper mapper = new ObjectMapper();
			StringWriter writer = new StringWriter();
			List<User> users = service.getUsersByName(userName, start, length, columnName, orderDir);
			Integer pageCount = service.getUsersPageCountByName(userName);
			map.put("data", users);
			map.put("recordsTotal", pageCount);
			map.put("recordsFiltered", pageCount);
			map.put("draw", draw);
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@ResponseBody
	@RequestMapping(value = "/user/updateUserPwd")
	public Integer updateUserPwd(HttpServletRequest request) {
		try {
			HttpSession session = request.getSession();
			String userName = (String) session.getAttribute("username");
			String passWordOld = (String) request.getParameter("passWordOld");
			String passWordNew = request.getParameter("passWordNew");
			if (userName == null) {
				// 您的登陆凭证已失效,请重新登陆后在试！
				return 1;
			}
			Integer num = service.verifyPassWord(userName, CommonUtils.MD5(passWordOld));
			if (num < 1) {
				// 原密码输入错误，请验证后在试！
				return 2;
			}
			Integer id = (Integer) session.getAttribute("id");
			service.updatePassWord(id, CommonUtils.MD5(passWordNew));
			return 0;
		} catch (Exception e) {
			e.printStackTrace();
			// 系统内部错误,请与管理员联系！
			return -1;
		}
	}
	
	@RequestMapping(value = "/accountManage")
	public ModelAndView accountManage() {
		long start = System.currentTimeMillis();
		ModelAndView mav = new ModelAndView("accountManage");
		mav.addObject("menuid", 10);
		long end = System.currentTimeMillis();
		logger.info("runing userManager function use times :" + (end - start));
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getAccountPage")
	public String getAccountPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		StringWriter writer = new StringWriter();
		String result = "";
		try {
			Integer draw = Integer.parseInt(request.getParameter("draw"));
			Integer start = Integer.parseInt(request.getParameter("start"));
			Integer length = Integer.parseInt(request.getParameter("length"));
			String userName = request.getParameter("userName");
			String year = request.getParameter("year");
			String orderColumn = request.getParameter("order[0][column]");
			String columnName = request.getParameter("columns[" + orderColumn + "][data]");
			String orderDir = request.getParameter("order[0][dir]");
			Pager<Account> pager = new Pager<>();
			Account dto = new Account();
			dto.setUserName(userName);
			dto.setYear(year);
			pager.setT(dto);
			pager.setPagenow(start / length + 1);
			pager.setSize(length);
			pager.setOrderCol(columnName);
			pager.setOrder(orderDir);
			Pager<List<Account>> accounts = accountService.findByCase(pager);
			map.put("data", accounts.getT());
			map.put("recordsTotal", accounts.getTotal());
			map.put("recordsFiltered", accounts.getTotal());
			map.put("draw", draw);
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
